package com.hjy.core.transport.netty.handler;

import com.hjy.common.entity.RpcRequest;
import com.hjy.common.entity.RpcResponse;
import com.hjy.core.handler.RequestHandler;
import com.hjy.core.provider.DefaultServiceProvider;
import com.hjy.core.provider.ServiceProvider;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

public class NettyServerHandler extends SimpleChannelInboundHandler<RpcRequest> {

    private static RequestHandler requestHandler;
    private static ServiceProvider serviceProvider;

    static {
        requestHandler = new RequestHandler();
        serviceProvider = new DefaultServiceProvider();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, RpcRequest msg) throws Exception {
        System.out.println("服务器收到请求: " + msg);
        String interfaceName = msg.getInterfaceName();
        Object service = serviceProvider.getService(interfaceName);
        Object result = requestHandler.handle(msg, service);
        ctx.writeAndFlush(RpcResponse.success(result));
    }
}
